package com.landerer.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.landerer.dto.EmployeeDTO;
import com.landerer.model.Employee;

@Stateless
public class EmployeeServiceAdaptor implements EmployeeServiceRemoteBusiness {
	
	@PersistenceContext(unitName="employeemgmt")
	private EntityManager entityManager;
	
	private EmployeeServiceBusiness servie = null;
	
	@PostConstruct
	public void initService() {
		this.servie = new EmployeeService(this.entityManager);
	}

	@Override
	public EmployeeDTO createEmployee(String name, long salary) {
		return mapEmployeeToEmployeeDTO(this.servie.createEmployee(name, salary));
	}

	@Override
	public EmployeeDTO findEmployeeById(long id) {
		return mapEmployeeToEmployeeDTO(this.servie.findEmployeeById(id));
	}

	@Override
	public List<EmployeeDTO> findAllEmployees() {
		List<EmployeeDTO> allEmployeeDTOs = new ArrayList<EmployeeDTO>();
		List<Employee> allEmployees = this.servie.findAllEmployees();
		for(Employee employee : allEmployees) {
			allEmployeeDTOs.add(mapEmployeeToEmployeeDTO(employee));
		}
		return allEmployeeDTOs;
	}

	private EmployeeDTO mapEmployeeToEmployeeDTO(Employee employee) {
		EmployeeDTO employeeDTO = new EmployeeDTO();
		employeeDTO.setId(employee.getId());
		employeeDTO.setName(employee.getName());
		employeeDTO.setSalary(employee.getSalary());
		return employeeDTO;
	}

	@Override
	public void deleteAllEmployees() {
		this.servie.deleteAllEmployees();
	}

	@Override
	public void updateEmployee(EmployeeDTO employeeDTO) {
		this.servie.updateEmployee(employeeDTO.getId(), employeeDTO.getName(), employeeDTO.getSalary());
	}
}
